# -*- encoding: utf-8 -*-
"""
App级的调用外部接口共通方法
"""

import json
import ssl
import urllib

from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError

from common import config


@gen.coroutine
def get_request_data(request_handler, request_url, ret_type='dict', method='GET', para_dict=None):
    """
    通过指定的url来获取数据
    :param request_handler: 请求数据的request_handler
    :param request_url: 请求数据的url
    :param ret_type:  返回的数据格式 如 'dict' | 'list'
    :param method:  请求的方式 如 GET|POST
    :param para_dict:  post请求时参数字典
    :return: 获取请求的数据
    """
    client = AsyncHTTPClient()
    try:
        context = None
        version = get_tornado_version()
        if request_url.split(':', 1)[0] == "https":
            context = ssl._create_unverified_context()
        if version >= '4.2':
            if method == 'GET' or method == 'DELETE':
                response = yield client.fetch(
                    request_url, method=method, ssl_options=context)
                res = json.loads(response.body)
            elif method == 'POST':
                response = yield client.fetch(
                    request_url,
                    method=method,
                    body=json.dumps(para_dict, ensure_ascii=False),
                    ssl_options=context)
                res = json.loads(response.body)
            else:
                res = {}
        else:
            if method == 'GET' or method == 'DELETE':
                response = yield client.fetch(
                    request_url, method=method)
                res = json.loads(response.body)
            elif method == 'POST':
                response = yield client.fetch(
                    request_url,
                    method=method,
                    body=json.dumps(para_dict, ensure_ascii=False))
                res = json.loads(response.body)
            else:
                res = {}
    except HTTPError, ex:
        if ret_type == 'dict':
            res = {'code': '1003', 'msg': config.CODE1047}
        elif ret_type == 'list':
            res = {'code': '1003', 'msg': config.CODE1047, 'info': []}
    raise gen.Return(res)


def get_tornado_version():
    """
    获取当前机器安装tornado 版本
    :return:
    """
    import sys
    import tornado
    tornado_module = sys.modules.get('tornado')
    if tornado_module:
        return tornado_module.version
    else:
        return '4.1'
